package org.dearsor.elective.service;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Transient;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dearsor.elective.exception.CreditOverflowExeption;
import org.dearsor.elective.model.Course;
import org.dearsor.elective.model.Person;
import org.dearsor.elective.model.Student;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Repository
public class CourseMgr {
	
	public static final Log log = LogFactory.getLog(CourseMgr.class);
	
	public static int LIMIT = 10;
	
	@PersistenceContext
	private EntityManager em;
	
	
	
	@Transactional
	public void doSelect(long courseId,Person user) throws DataAccessException,CreditOverflowExeption {
		user = em.merge(user);
		Course course = em.find(Course.class, courseId);
		if (((Student) user).getTotalScore() + course.getScore() < LIMIT) {
			((Student) user).getCourses().add(course);
		} else {
			String message = "所选课程累计学分超过限制（最大为 " + LIMIT + "）";
			log.info(message);
			throw new CreditOverflowExeption(message);
		}
		
	}
	
	@Transactional
	public void doUnselect(long courseId,Person user)  throws DataAccessException {
		Course course = em.find(Course.class, courseId);
		((Student) em.merge(user)).getCourses().remove(course);
		
	}
	
	@Transactional(readOnly = true)
	public static boolean checkSelect(Person user,Course course) throws DataAccessException {
		return ((Student) user).getCourses().contains(course);
	}
	
	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<Course> listCourses() throws DataAccessException {
		return em.createQuery("select c from Course c").getResultList();
	}

	@Transactional(readOnly = true)
	public List<Course> listAvailableCourses(Person person) throws DataAccessException {
		
		List<Course> courses = listCourses();
		courses.removeAll(((Student) em.merge(person)).getCourses());
		return courses;
	}

}
